<?xml version="1.0" encoding="UTF-8"?>
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="./css/template.css" />
        <link type="text/css" rel="stylesheet" href="./css/SyntaxHighlighter.css" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Serial port use in Java</title>
        <script language="javascript" src="./js/shInit.js" />
        <script language="javascript" src="./js/shCore.js" />
        <script language="javascript" src="./js/shBrushCpp.js" />
        <script language="javascript" src="./js/shBrushCSharp.js" />
        <script language="javascript" src="./js/shBrushCss.js" />
        <script language="javascript" src="./js/shBrushDelphi.js" />
        <script language="javascript" src="./js/shBrushJava.js" />
        <script language="javascript" src="./js/shBrushJScript.js" />
        <script language="javascript" src="./js/shBrushPhp.js" />
        <script language="javascript" src="./js/shBrushPython.js" />
        <script language="javascript" src="./js/shBrushRuby.js" />
        <script language="javascript" src="./js/shBrushSql.js" />
        <script language="javascript" src="./js/shBrushVb.js" />
        <script language="javascript" src="./js/shBrushXml.js" />
        <keywords>serial port</keywords>
        <author>Stéphane ARNAULT</author>
    </head>
    <body>
        <div class="chapter">
            <h2>Introduction</h2>
            <p>
                In this article, i will discribe how to use the micro-computer serial port in the Java programming language throught JavaComm API
                (application programming interface) 
                <br />
                This interface enable build software that allow to control modem, router or every all component that connects on serial/parallel port
                of your compunter.  
            </p>
            <p>In the first time, we will see a fews generalities about serial port, then we will consider the pre required 
                and the JavaComm API installation before moving to the description of functionalities and Java programming.	
            </p>
        </div>
        <div class="chapter">
            <h2>1. Generality about serial port</h2>
            <p>
                <br />
                The serial interface is an asynchronous interface, which means that the signal of this interface is not synchronized with that of a bus.
                The bits of data are sent one after the other. A character is generally composed of a set of eight bits. This value is therefore between 0 and
                255 (2 power 8) and is stored on 1 byte (ie 8 bits). Each character is defined by a begin signal which is a bit to 0 
                and a standard end signal which may be one or two bits end, it helps to indicate that the character has been sent.
                The asynchronous's interface is oriented character, indeed, one must use the beginning signals and end to identify a character. 
                The disadvantage of this method is increasing the duration of transfers of almost 25%. In effect for each line of 8 bits it takes a minimum of 2 bits.
                The term "serial" is just because the bits are sent one after the other on a single wire for the issuance and another wire for the reception, as for
                the phone. There are numerous expansion card enable to have several serial port or parallel port.
                To "transform" the data to send into bit suite serialized, the computer uses a small chip, UART.
                <br />
            </p>
            <table width="70%" border="0" align="center" cellpadding="0" cellspacing="0">
                <tbody>
                    <tr>
                        <td>
                            <img src="./images/schema1.jpg" width="111" height="196" />
                        </td>
                        <td>
                            DB9 connector
                            <br />
                            1 - DCD, Data Carrier Detect
                            <br />
                            2 - TxD, Transmission du signal
                            <br />
                            3 - ExD, Réception du signal
                            <br />
                            4 - DTR, Data Terminal Ready
                            <br />
                            5 - GND, Masse électrique
                            <br />
                            6 - DSR, Data Set Ready
                            <br />
                            7 - CTS, Clear To Send
                            <br />
                            8 - RTS, Request To Send
                            <br />
                            9 - RI, Ring Indicator
                        </td>
                    </tr>
                </tbody>
            </table>
            <p align="center">
                <em>Serial port schema</em>
            </p>
            <p>
                <br />
                In this article, we will not see the physical functioning of the serial port
                (matching pin, operation of the chip UART) as the physical part
                is completely transparent to the programmer.
                <br />
            </p>
        </div>
        <div class="chapter">
            <h2>2. Installation</h2>
            <div class="subChapter">
                <h3>2.1. Pre Required</h3>
                <p>Several prerequisites are necessary to use the serial port in a Java program.</p>
                <p>
                    • First, a serial port must be present on the micro-computer, it will be used to transmit data.
                    <br />
                    • A Java compiler available on the official website of Sun http://java.sun.com which can generate byte code from the source code in Java.
                    <br />
                    • The "Java Communications API " must be downloaded and installed, this step will be detailed in Part 4 of this article. 
                    <br />
                    • A virtual machine is required to implement the program.
                </p>
                <p>When all these prerequisites are made, we can finally move to the programming that allow to control the serial port.</p>
                <h3>2.2. Installations</h3>
                <p>	The installation of the API JavaComm not obvious to many programmers, I preferred to detail step by step how to proceed.
                The JavaComm package is available on the official website of Sun at the following address: http://java.sun.com/products/javacomm/. It the first time you have to
                download the latest version, which corresponds to your development platform. The examples that we see in this article will be adapted to Windows
                operating systems but the way forward is the same for Solaris and Linux for example. Unfortunately, there is no version for MacOS.
               </p>
                <p>To place the necessary files in order to install JavaComm, we will assume that the JDK is installed in the directory c:\java and the virtual machine
                in the directory c:\java\jre\, you must change the paths that follow depending on your configuration.
                You should check that: 
               </p>
                • The file win32com.dll is in c:\java\bin.
                <br />
                • The file comm.jar is in c:\java\lib et c:\java\jre\lib\ext.
                <br />
                • The file javax.comm.properties is in c:\java\lib.
                <br />
                All these files are contained in the archive that you downloaded earlier.
                To compile, you have to have the file comm.jar in the directory c:\java\jre\lib\ext.
                We must also define a new environment variable to reference classes contains in comm.jar package:
                <br />
                set CLASSPATH=%classpath%;c:\java\lib\comm.jar;.
                <br />
                It is imperative that the package JAVACOMM be placed on the same logical drive which contains the JDK in order the program works.
                <br />	
                That is to say that the .class of your executable must be on the C drive if the JDK is in the directory c:\\Java.
                <br />
                Now that everything is installed, you can deal with the functioning of the API.
                <br />
            </div>
            <h2>3. API communication in Java</h2>
            <div class="subChapter">
                <h3>3.1. Theory</h3>
                <p>                    	
                The JavaComm API (Java communications API) that we have previously installed can manage communications with the serial port (RS232) or
                the parallel port (IEEE 1284) in a simplified manner and independently of the platform used.
                    <br />
                    The documentation in English on the classes package is on
                    <br />
                    http://java.sun.com/products/javacomm/javadocs/API_users_guide.html
                </p>
                <p>	
                    This API adds another native layer which is the interface between hardware and software java, as shown below.</p>
                <p align="center">
                    <img src="./images/schema2.jpg" width="355" height="300" />
                    <br />
                </p>
                <p>
                    With this API it is not not need to worry about equipment, transfers are automatically managed.
                    <br />                        	
                    Communication through the serial port is done by a flood of data.
                    We must therefore begin by defining a BufferedReader and a PrintWriter
                    which will be used to send and receive data, and then instantiate
                    a CommPortIdentifier which defines the port to use and a SerialPort
                    Which manages the serial connection. The parameters of the serial connection
                    are set thanks to the method of class setSerialPortParams
                    SerialPort.
                    <br />                	
                    We will implement this brief description of the API in the next part of this article in order to better understand its functioning.
                </p>
                <h3>3.2. Setting practice</h3>  	
                To clarify the theoretical information that we have seen previously on the functioning of the JavaComm API, we will now see a
                concrete example of use with a comprehensive program that establishes a connection on Com1 port and sends a string.
                <br />
            </div>
            <textarea name="code" class="java" rows="50" cols="50">import javax.comm.*;
				import java.io.*;
				import java.util.*;
				/*			
                This class can test the serial ports available
                by listing and then creating a stream of entry and exit
				*/
				public class TesteJavaComm
				{
				CommPortIdentifier portId;
				BufferedReader in;
				PrintWriter out;
				SerialPort serialPort;
				/*
				Constructor of TesteJavaComm class that take in parameter the serial port to use.				
                In a first step list available ports on the pc
				*/
				public TesteJavaComm (String com)
				{
				System.out.println("listage des ports série disponibles:");
				listePortsDispo();
				try
				{
				//Serial port opening:
				portId=CommPortIdentifier.getPortIdentifier(com);
				serialPort=(SerialPort)portId.open("Envoi",2000);
				//it selects all the parameters of the serial connection:
				serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
				System.out.println("Ouverture du port "+com);
				//for reading and writing with streams:
				in=new BufferedReader(
				new InputStreamReader(serialPort.getInputStream()));
				out=new PrintWriter(serialPort.getOutputStream());
				//Test of read/write on the serial port
				String originalText="une chaine de caractere";
				outputArray = originalText.getBytes( );
				out.write ( outputArray, 0 , length );
				int b = in.read()
				in.close();
				out.close();
				}
				catch (Exception e)
				{
				e.printStackTrace();
				}
				}//constructor end
				public void listePortsDispo()
				{
				System.err.println("recherche...");
				Enumeration portList=CommPortIdentifier.getPortIdentifiers();
				if (portList==null)
				{
				System.err.println("Aucun port de communication détecté");
				return;
				}
				while (portList.hasMoreElements())
				{
				portId=(CommPortIdentifier)portList.nextElement();
				System.out.println("* "+portId.getName());
				} // while
				} //method listePortsDispo() end
				/*
				Main methode that can test our class testing by opening a connection on port COM1.
				*/
				public static void main(String args[])
				{
				new TesteJavaComm ("COM1");
				}//main end
				}//Class end</textarea>
            <h2>Conclusion</h2>
            <p>         	
                We have seen how to communicate with the serial port programming
                Java.
                <br /> 	
                The API that we used in this example also allows communication
                by the parallel port with a functioning roughly
                similar.
                <br />
                It remains that that API has an uncertain future. Despite the Linux porting recently, 
                it still not existe an  official porting of this API for MacOs
                that count an non-negligible market share.
                <br />	
                In addition, USB ports are now a standard in recent years which has completely engulfed the serial port.
                Serial port is used in rare professionals applications 
            </p>
        </div>
    </body>
</html>

